﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebSocketStressTesting
{
    public partial class MainForm : Form
    {


        private Main main;
        private Dictionary<string, string> dictionary;

        public MainForm()
        {
            this.dictionary = new Dictionary<string, string>();
            InitializeComponent();
        }

       /// <summary>
       /// 是否激活控件
       /// </summary>
       /// <param name="flag"></param>
        private void IsEnabled(bool flag)
        {
            if (!flag)
            {
                this.btnStart.Enabled = false;
                this.cboAnswer.Enabled = false;
                this.rtxtAnswer.Enabled = false;
                this.rtxtFirst.Enabled = false;
                return;
            }
            this.btnStart.Enabled = true;
            this.cboAnswer.Enabled = true;
            this.rtxtAnswer.Enabled = Main.IsAnswer;
            this.rtxtFirst.Enabled = true;
        }

        /// <summary>
        /// 获取配置文件
        /// </summary>
        /// <returns></returns>
        private string getConfig()
        {
            if (!Directory.Exists(Application.StartupPath + "\\"))
            {
                Directory.CreateDirectory(Application.StartupPath + "\\");
            }
            if (!File.Exists(Application.StartupPath + "\\setting.ini"))
            {
                StreamWriter streamWriter = new StreamWriter(Application.StartupPath + "\\setting.ini", false, Encoding.Default);
                streamWriter.Write("IP=127.0.0.1\r\nPort=29000\r\nConn=1000\r\nAnswer=true\r\nFirstStr=1\r\nAnsStr=2");
                streamWriter.Close();
                streamWriter.Dispose();
            }
            StreamReader streamReader = new StreamReader(Application.StartupPath + "\\setting.ini", Encoding.Default);
            string result = streamReader.ReadToEnd();
            streamReader.Close();
            streamReader.Dispose();
            return result;
        }

        /// <summary>
        /// 写入配置文件
        /// </summary>
        private void WriteConfig()
        {
            StreamWriter streamWriter = new StreamWriter(Application.StartupPath + "\\setting.ini", false, Encoding.Default);
            streamWriter.Write(string.Concat(new string[]
            {
                "IP=",
                this.cboServerIP.Text.Trim(),
                "\r\nPort=",
                this.nudServerPort.Text.Trim(),
                "\r\nConn=",
                this.nudConnectNum.Text.Trim(),
                "\r\nAnswer=",
                this.cboAnswer.Checked.ToString(),
                "\r\nFirstStr=",
                this.rtxtFirst.Text.Trim(),
                "\r\nAnsStr=",
                this.rtxtAnswer.Text.Trim()
            }));
            streamWriter.Close();
            streamWriter.Dispose();
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <returns></returns>
        private Dictionary<string, string> ReadConfig()
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            string[] array = this.getConfig().Trim().Replace("\r\n", "=").Split(new char[]
            {
                '='
            });
            for (int i = 0; i < array.Length; i += 2)
            {
                dictionary.Add(array[i], array[i + 1].Trim());
            }
            return dictionary;
        }

        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.dictionary = this.ReadConfig();
                this.nudServerPort.Text = this.dictionary["Port"];
                this.nudConnectNum.Text = this.dictionary["Conn"];
                this.cboAnswer.Checked = bool.Parse(this.dictionary["Answer"]);
                this.rtxtFirst.Text = this.dictionary["FirstStr"];
                this.rtxtAnswer.Text = this.dictionary["AnsStr"];
                this.cboServerIP.Items.AddRange(Main.GetIPAddress());
                this.cboServerIP.Text = this.dictionary["IP"];
            }
            catch
            {
                MessageBox.Show("读取配置文件失败！");
            }
        }

        /// <summary>
        /// 开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (this.btnStart.Enabled)
            {
                try
                {
                    if (int.Parse(this.nudConnectNum.Text) > 50000)
                    {
                        MessageBox.Show("压力测试单台上限为50000个连接");
                    }
                    else
                    {
                        byte[] bytes = Encoding.Default.GetBytes(this.rtxtFirst.Text.Trim());
                        byte[] bytes2 = Encoding.Default.GetBytes(this.rtxtAnswer.Text.Trim());
                        if (bytes.Length < 120 && bytes2.Length < 120)
                        {
                            new Thread(new ParameterizedThreadStart(this.SendData))
                            {
                                IsBackground = true
                            }.Start(new string[]
                            {
                                this.cboServerIP.Text,
                                this.nudServerPort.Text,
                                this.nudConnectNum.Text,
                                this.rtxtFirst.Text.Trim(),
                                this.rtxtAnswer.Text.Trim()
                            });
                            this.IsEnabled(false);
                            this.WriteConfig();
                        }
                        else
                        {
                            MessageBox.Show("发送数据的长度需小于120字节！");
                            this.IsEnabled(true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.IsEnabled(true);
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void SendData(object obj)
        {
            string[] array = (string[])obj;
            this.main = new Main(array[0], int.Parse(array[1]), int.Parse(array[2]));
            this.main.SendAnswerData(array[3], array[4]);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            this.lblSuccessNum.Text = Main.SuccessNum.ToString();
            this.lblFailNum.Text = Main.FailNum.ToString();
            this.lblSendNum.Text = Main.SendNum.ToString();
            if (this.lblFailNum.Text == this.nudConnectNum.Text)
            {
                this.IsEnabled(true);
            }
        }

        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }

        /// <summary>
        /// 是否自动应答
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboAnswer_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cboAnswer.Checked)
            {
                Main.IsAnswer = true;
                this.rtxtAnswer.Enabled = true;
                return;
            }
            Main.IsAnswer = false;
            this.rtxtAnswer.Enabled = false;
        }
        
    }
}
